<template>
  <div style="color:red;font-size:24px;">调试标记：DeviceActionDialog.vue</div>
  <el-dialog
    v-model:visible="dialogVisible"
    :title="dialogTitle"
    width="400px"
    :z-index="3000"
    @close="onClose"
  >
    <el-form :model="actionForm">
      <el-form-item v-if="actionType === 'inspection'" label="设备状态">
        <el-select v-model="actionForm.status" placeholder="请选择设备状态">
          <el-option label="正常运行" value="正常运行" />
          <el-option label="异常" value="异常" />
          <el-option label="维修中" value="维修中" />
          <el-option label="备用" value="备用" />
          <el-option label="报废" value="报废" />
        </el-select>
      </el-form-item>
      <el-form-item v-if="actionType === 'inspection' && actionForm.status === '异常'" label="异常描述">
        <el-input v-model="actionForm.repairDesc" type="textarea" :rows="2" placeholder="请填写异常描述" />
      </el-form-item>
      <el-form-item v-if="actionType === 'repair'" label="故障描述">
        <el-input v-model="actionForm.content" type="textarea" :rows="3" placeholder="请填写故障描述" />
      </el-form-item>
      <el-form-item label="操作人">
        <el-input v-model="actionForm.operator" placeholder="请输入操作人" />
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="close">取消</el-button>
      <el-button type="primary" @click="submitAction">提交</el-button>
    </template>
  </el-dialog>
</template>

<script setup>
import { ref, watch, defineProps, defineEmits, computed } from 'vue'
import AV from '../leancloud'
import { ElMessage } from 'element-plus'

const props = defineProps({
  visible: Boolean,
  actionType: String, // 'inspection' | 'calibration' | 'repair'
  deviceId: String,
  deviceName: String,
  deviceModel: String,
  deviceCode: String,
  deviceLocation: String,
  onSuccess: Function
})
const emit = defineEmits(['update:visible'])

const dialogVisible = computed({
  get: () => props.visible,
  set: v => emit('update:visible', v)
})

watch(dialogVisible, v => {
  // 对话框可见性变化
});

const actionForm = ref({ content: '', operator: '', status: '', repairDesc: '' })

const dialogTitle = computed(() => {
  switch (props.actionType) {
    case 'inspection': return '日常检查';
    case 'calibration': return '校正';
    case 'repair': return '报修';
    default: return '';
  }
})

watch(() => props.visible, v => {
  if (v) {
    actionForm.value = { content: '', operator: '', status: '', repairDesc: '' }
    // 优先用localStorage里的操作人
    const lastOperator = localStorage.getItem('operator') || ''
    actionForm.value.operator = lastOperator
  }
})

function close() {
  emit('update:visible', false)
}
function onClose() {
  emit('update:visible', false)
}

function generateRepCode() {
  const now = new Date();
  const y = now.getFullYear();
  const m = String(now.getMonth() + 1).padStart(2, '0');
  const d = String(now.getDate()).padStart(2, '0');
  const h = String(now.getHours()).padStart(2, '0');
  const min = String(now.getMinutes()).padStart(2, '0');
  const s = String(now.getSeconds()).padStart(2, '0');
  return `BX${y}${m}${d}${h}${min}${s}${Math.floor(Math.random()*1000).toString().padStart(3,'0')}`;
}

async function submitAction() {
  alert('submitAction 被触发');
  console.log('submitAction 被触发');
  if (props.actionType === 'calibration') {
    if (!actionForm.value.operator) {
      ElMessage.error('请填写操作人');
      return;
    }
    console.log('校正 deviceId:', props.deviceId); // 打印 deviceId
    try {
      const CalibrationRecord = AV.Object.extend('DeviceActionRecord');
      const record = new CalibrationRecord();
      record.set('device', AV.Object.createWithoutData('Device', props.deviceId));
      record.set('type', '校正');
      record.set('content', '日常校正');
      record.set('operator', actionForm.value.operator);
      record.set('date', new Date());
      record.set('result', '完成');
      record.set('status', '正常');
      await record.save();
      ElMessage.success('校正已提交');
      close();
      props.onSuccess && props.onSuccess();
    } catch (e) {
      ElMessage.error('校正保存失败: ' + (e.message || e.rawMessage));
      console.error('校正保存失败', e);
    }
    return;
  } else if (props.actionType === 'repair') {
    if (!actionForm.value.content || !actionForm.value.operator) {
      ElMessage.error('请填写故障描述和操作人');
      return;
    }
    console.log('报修 deviceId:', props.deviceId);
    try {
      const RepairRecord = AV.Object.extend('RepairRecord');
      const record = new RepairRecord();
      record.set('device', AV.Object.createWithoutData('Device', props.deviceId));
      record.set('desc', actionForm.value.content);
      record.set('reporter', actionForm.value.operator);
      record.set('reportTime', new Date());
      record.set('status', '处理中');
      record.set('repCode', generateRepCode());
      const acl = new AV.ACL();
      acl.setPublicReadAccess(true);
      acl.setPublicWriteAccess(true);
      record.setACL(acl);
      await record.save();
      ElMessage.success('报修已提交');
      // 钉钉推送
      const cloudFuncUrl = 'https://hellowodingtalk-lsmprvoblr.cn-beijing.fcapp.run';
      const msg = { content: `【设备报修通知】\n\n设备名称：${props.deviceName}\n规格型号：${props.deviceModel || ''}\n设备编号：${props.deviceCode}\n安装地点：${props.deviceLocation || '无'}\n报修内容：${actionForm.value.content}\n报修人：${actionForm.value.operator}\n报修时间：${new Date().toLocaleString()}` };
      try {
        const res = await fetch(cloudFuncUrl, {
          method: 'POST',
          headers: { 'Content-Type': 'application/json' },
          body: JSON.stringify(msg)
        });
        const data = await res.json();
        if (data.errcode === 0) {
          ElMessage.success('报修已提交并推送钉钉');
        } else {
          ElMessage.error('钉钉推送失败：' + (data.errmsg || JSON.stringify(data)));
        }
      } catch (e) {
        ElMessage.error('钉钉推送异常：' + e.message);
      }
      close();
      props.onSuccess && props.onSuccess();
    } catch (e) {
      ElMessage.error('报修保存失败: ' + (e.message || e.rawMessage));
      console.error('报修保存失败', e);
    }
    return;
  } else if (props.actionType === 'inspection') {
    if (!actionForm.value.status || !actionForm.value.operator) {
      ElMessage.error('请填写设备状态和操作人');
      return;
    }
    if (actionForm.value.status === '异常' && !actionForm.value.repairDesc) {
      ElMessage.error('请填写异常描述');
      return;
    }
    console.log('检查 deviceId:', props.deviceId);
    try {
      const InspectionRecord = AV.Object.extend('DeviceActionRecord');
      const record = new InspectionRecord();
      record.set('device', AV.Object.createWithoutData('Device', props.deviceId));
      record.set('type', '日常检查');
      record.set('content', actionForm.value.status);
      record.set('operator', actionForm.value.operator);
      record.set('date', new Date());
      let result = '完成';
      let status = actionForm.value.status === '正常运行' ? '正常' : (actionForm.value.status === '异常' ? '异常' : actionForm.value.status);
      if (actionForm.value.status === '异常') {
        result = '报修';
        status = '异常';
      }
      record.set('result', result);
      record.set('status', status);
      await record.save();
      // 更新设备状态
      const deviceObj = AV.Object.createWithoutData('Device', props.deviceId);
      deviceObj.set('status', actionForm.value.status);
      await deviceObj.save();
      // 如果选择异常，自动报修
      if (actionForm.value.status === '异常') {
        try {
          const RepairRecord = AV.Object.extend('RepairRecord');
          const repair = new RepairRecord();
          repair.set('device', AV.Object.createWithoutData('Device', props.deviceId));
          repair.set('desc', actionForm.value.repairDesc);
          repair.set('reporter', actionForm.value.operator);
          repair.set('reportTime', new Date());
          repair.set('status', '处理中');
          repair.set('repCode', generateRepCode());
          const acl = new AV.ACL();
          acl.setPublicReadAccess(true);
          acl.setPublicWriteAccess(true);
          repair.setACL(acl);
          await repair.save();
          // 钉钉推送
          const cloudFuncUrl = 'https://hellowodingtalk-lsmprvoblr.cn-beijing.fcapp.run';
          const msg = { content: `【设备报修通知】\n\n设备名称：${props.deviceName}\n规格型号：${props.deviceModel || ''}\n设备编号：${props.deviceCode}\n安装地点：${props.deviceLocation || '无'}\n报修内容：${actionForm.value.repairDesc}\n报修人：${actionForm.value.operator}\n报修时间：${new Date().toLocaleString()}` };
          try {
            const res = await fetch(cloudFuncUrl, {
              method: 'POST',
              headers: { 'Content-Type': 'application/json' },
              body: JSON.stringify(msg)
            });
            const data = await res.json();
            if (data.errcode === 0) {
              ElMessage.success('异常已自动报修并推送钉钉');
            } else {
              ElMessage.error('钉钉推送失败：' + (data.errmsg || JSON.stringify(data)));
            }
          } catch (e) {
            ElMessage.error('钉钉推送异常：' + e.message);
          }
        } catch (e) {
          ElMessage.error('自动报修保存失败: ' + (e.message || e.rawMessage));
          console.error('自动报修保存失败', e);
        }
      } else {
        ElMessage.success('检查已提交');
      }
      close();
      props.onSuccess && props.onSuccess();
    } catch (e) {
      ElMessage.error('检查保存失败: ' + (e.message || e.rawMessage));
      console.error('检查保存失败', e);
    }
    return;
  }
}
</script> 